package com.mages.classification.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class LogsService {

    public static String log_dir;
    public List<String> LogsArray = new ArrayList<>();

    @Value("${SERVICE_LOG:share/log}")
    public void setLog_dir(String log_dir) {
        this.log_dir = log_dir;
    }

    public List<String> ReadLogs(){
        String encoding="GBK";
        File file=new File(log_dir);
        String[] Logfiles = file.list();

        for(String filename : Logfiles){
            File logfile=new File(log_dir+File.separator+filename);
            if(logfile.isFile() && logfile.exists()) { //判断文件是否存在
                InputStreamReader read = null;//考虑到编码格式
                try {
                    read = new InputStreamReader(new FileInputStream(logfile), encoding);
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while ((lineTxt = bufferedReader.readLine()) != null) {
                        LogsArray.add(lineTxt);
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return LogsArray;
    }
}
